public without sharing class NCPrdouctRemindController {

	public String msg {get;private set;}
	public boolean isErr {get;private set;}
	public Boolean isSuccess {get;private set;}

	public String dataJson {get ; private set;}
	public String searchJson {get;  set;}
	public String saveJson {get;  set;}
	public String invalidPrId {get; set;}
    public class ControllerException extends Exception {}


    public NCPrdouctRemindController() {

    	getDetails();
        
    }

    public void getDetails(){

    	List<ProductRemindBean> tmp = new List<ProductRemindBean>();
    	for(ProductRemind__c pr :[select Id , Product__c,Product__r.ProductName__c , Product__r.NCCode__c,RemindContent__c, Product__r.Brand__c,
    		Product__r.Spec__c,EndDate__c,BatchCode__c  from ProductRemind__c where EndDate__c >:Date.today()
    		 Order by LastModifiedDate desc limit 200 ]){
    		tmp.add(new ProductRemindBean(pr));
    	}
    	dataJson = EncodingUtil.urlEncode(JSON.serialize(tmp), 'UTF-8');
    }
    public void setNil(){
    	dataJson = '[]';
    	searchJson = '{}';
    	saveJson = '[]';

    }
    public void getRemindDetails(){
        List<RemindBean> tmp = new List<RemindBean>();
        System.debug('getRemindDetails==>'+invalidPrId);
        for(ProductRemindDetails__c prd :[select NotePerson__r.Name , ProductRemind__r.Product__r.ProductName__c, Account__r.Name,
         ProductRemind__r.Product__r.NCCode__c,ProductRemind__r.BatchCode__c ,CreatedDate 
         from ProductRemindDetails__c where ProductRemind__c =:invalidPrId ]){
            tmp.add(new RemindBean(prd));
        }
        dataJson = EncodingUtil.urlEncode(JSON.serialize(tmp), 'UTF-8');
    }

    public void save(){
    	isSuccess = false; 
    	msg = '';
    	List<Object> saveList = (List<Object>) JSON.deserializeUntyped(EncodingUtil.urlDecode(saveJson, 'UTF-8'));

    	if(saveList.size() == 0) return;

    	List<ProductRemind__c> prList = new List<ProductRemind__c>();
    	Set<String> nccodes = new Set<String>();
    	Set<String> batchcodes  = new Set<String>();
    	for(Object o : saveList){
    		Map<String,Object> mo = (Map<String,Object>) o ; 
    		nccodes.add(DataUtil.getStringValue(mo.get('invcode')));
    		batchcodes.add(DataUtil.getStringValue(mo.get('vbatchcode')));
    	}
    	Map<String,Id  > prMap = new Map<String,Id  > ();
    	for(ProductRemind__c pr : [select Id,Product__r.NCCode__c ,BatchCode__c  from ProductRemind__c where Product__r.NCCode__c in: nccodes and BatchCode__c in: batchcodes]){
    		prMap.put(pr.Product__r.NCCode__c +'-'+pr.BatchCode__c,pr.Id );
    	}
    	Map<String ,Product__c> productMap = ImportObject.getProudctMap(nccodes);
    	nccodes.clear();

    	for(Object o : saveList){

    		Map<String,Object> mo = (Map<String,Object>) o ; 
    		ProductRemind__c pr = new ProductRemind__c();
    		if(!productMap.containsKey(DataUtil.getStringValue(mo.get('invcode')))){

    			msg = 'Salesforce里没有匹配到产品:' + DataUtil.getStringValue(mo.get('invname')) + '-'+DataUtil.getStringValue(mo.get('invcode'));
    			return;
    		}
    		pr.Product__c = productMap.get(DataUtil.getStringValue(mo.get('invcode'))).Id ;
    		
    		
    		pr.BatchCode__c = DataUtil.getStringValue(mo.get('vbatchcode'));
    		pr.EndDate__c =(DataUtil.getStringValue(mo.get('dvalidate')) == null || DataUtil.getStringValue(mo.get('dvalidate'))=='') ? null  :  Date.valueOf(DataUtil.getStringValue(mo.get('dvalidate')));
    		String key =  DataUtil.getStringValue(mo.get('invcode')) +'-' + pr.BatchCode__c ; 
            pr.RemindContent__c = DataUtil.getStringValue(mo.get('note'));
    		if(prMap.containsKey(key))pr.Id = prMap.get(key);
    		prList.add(pr);
    	}
    	SavePoint sp = Database.setSavepoint();
    	try {

    		if(prList.size() > 0) upsert  prList;
    		  getDetails();

    		msg = '保存成功!';
    		isSuccess = true; 
    	}catch (Exception e) {

    	    Database.rollback(sp);
    	    msg = '保存失败:'+e.getMessage();

    	}
    	

    }

    public void searchNCProduct(){

    	Map<String,Object> searchMap = ( Map<String ,Object> ) JSON.deserializeUntyped(EncodingUtil.urlDecode(searchJson, 'UTF-8'));

    	//String startDate =searchMap.get('startDate') == null ? Date.today().format() :  DataUtil.getStringValue(searchMap.get('startDate'))  ;


    	String sql = ' select  a.vbillcode , a.vnote ,b.cgeneralbid  , d.dvalidate  ,'+
     	'c.b.cinvbasid ,c.invcode ,b.vbatchcode ,c.invname, c.invmnecode ,c.invpinpai  ,c.invspec  ,c.invtype ,b.ninnum      from ic_general_h a '+
     	'   left outer join ic_general_b b      on a.cgeneralhid = b.cgeneralhid ' +
        ' left outer join bd_invbasdoc c    on b.cinvbasid = pk_invbasdoc   left outer join scm_batchcode d on d.pk_invbasdoc =  b.cinvbasid and b.vbatchcode = d.vbatchcode '+
        ' where a.dr = 0     and b.dr = 0 '+     
		'and b.cbodybilltypecode = \'46\' '+ 
   		'and a.pk_corp in (\'1001\' ,\'1006\') '+
    	'and a.fbillflag in (\'3\',\'4\')  '+ 

      	//'and a.dbilldate>=\''+startDate+'\' '+
    	'and substr(c.invcode ,1,1) = \'1\' '+
        ' and substr(c.invcode ,1,2) != \'10\'  ';
       //	'and a.vbillcode like \'%07%\'   ' ; 

        if(searchMap.get('endDate') != null ) sql +=  ' and a.dbilldate <=\''+DataUtil.getStringValue(searchMap.get('endDate'))+'\' ';
        if(searchMap.get('startDate') != null ) sql +=  ' and a.dbilldate >=\''+DataUtil.getStringValue(searchMap.get('startDate'))+'\' ';

        if(searchMap.get('nccode') != null ) sql +=  ' and c.invcode =\''+DataUtil.getStringValue(searchMap.get('nccode'))+'\' ';
        if(searchMap.get('serialno') != null ) sql +=  ' and c.invmnecode =\''+DataUtil.getStringValue(searchMap.get('serialno'))+'\' ';
        if(searchMap.get('brand') != null ) sql +=  ' and c.invpinpai like \'%'+DataUtil.getStringValue(searchMap.get('brand'))+'%\' ';
        if(searchMap.get('spec') != null ) sql +=  ' and c.invspec like \'%'+DataUtil.getStringValue(searchMap.get('spec'))+'%\' ';
        if(searchMap.get('batchcode') != null ) sql +=  ' and b.vbatchcode like \'%'+DataUtil.getStringValue(searchMap.get('batchcode'))+'%\' ';

      //  'and b.vbatchcode in  (\''+String.join(new List<String>(bcodes), '\',\'')+'\') ';

        System.debug('NCProductRemindUtil==>'+sql);

         String url = Label.queryResposityURL;

         sql =  'select a.*,rownum from ('+ sql+  ') a  where rownum <= 200 ';
        sql = '{"data":"'+sql+'"}';
        //请求

        HttpRequest req = new HttpRequest();
        req.setBody(sql);
        req.setMethod('POST');
        req.setHeader('Content-Type','text/plain');
        req.setEndpoint(url);
        HttpResponse res = Utils.postRequest(req, 2);
      ///返回结果处理
        if (res.getStatusCode() == 200) {
            if(System.Test.isRunningTest()){
                dataJson =  EncodingUtil.urlEncode('[{"vbillcode":"001234","invcode":"xx001","dvalidate":"2025-01-01"}]', 'UTF-8');
            }else{
                dataJson =  EncodingUtil.urlEncode(res.getBody(), 'UTF-8');
            }
        	
       
      }else{
      	 dataJson = '{}';
      }

    }
    public void setPrInvalid(){
    	isSuccess = false;
    		try {
    		  if(Id.valueOf(invalidPrId).getSobjecttype() != ProductRemind__c.SObjectType) throw new ControllerException('参数异常!'); 
    		}catch (Exception e) {
    		    msg = '参数异常!';
    		    return;
    		}
    		   	
    	SavePoint sp = Database.setSavepoint();

    	try {

    	    ProductRemind__c pr = new ProductRemind__c(Id=invalidPrId,EndDate__c=Date.today());
    		update pr ;

    		msg = '操作成功!';
    		getDetails();
    		isSuccess = true; 
    	}catch (Exception e) {
    		Database.rollback(sp);
    	    msg = '操作失败!'+e.getMessage();

    	}
    	
    	

    }


     //设置错误
    private void setError(String message){
    	isErr = true;
      throw new ControllerException(message);

    }

    public class RemindBean{
        public String uname ; 
        public String pname ; 
        public String nccode; 
        public String batchcode; 
        public String reminddate ;
        public String account ; 
        public RemindBean(ProductRemindDetails__c prd ){
            uname = prd.NotePerson__r.Name ; 
            pname = prd.ProductRemind__r.Product__r.ProductName__c;
            nccode = prd.ProductRemind__r.Product__r.NCCode__c ;
            batchcode = prd.ProductRemind__r.BatchCode__c;
            reminddate = prd.CreatedDate.format('yyyy年MM月dd日');
            account = prd.Account__r.Name ; 
        }


    }
    public class ProductRemindBean{

    	public String prId ; 
    	public String productName ; 
    	public String nccode ; 
    	public String spec ; 
    	public String batchcode ; 
    	public String dvalidate ; 
        public String note ; 
        public String brand ; 

    	public ProductRemindBean(ProductRemind__c pr ){

    		prId = pr.Id ; 
    		productName  = pr.Product__r.ProductName__c ; 
    		nccode = pr.Product__r.NCCode__c ; 
    		spec = pr.Product__r.Spec__c;
            brand = pr.Product__r.Brand__c;
    		batchcode = pr.BatchCode__c;

    		dvalidate = pr.EndDate__c  == null ? '' : pr.EndDate__c.format();
            note  = pr.RemindContent__c; 

    	}

    }

}